<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>键盘事件（写在document上）</title>
		<style>
			*{
				padding:0;
				margin:0;
			}
			img{
				position: absolute;
				top:300px;
				left: 400px;
				width: 100px;
			}
		</style>
	</head>
	<body>
		<img src="a1.png" alt="">
	</body>
</html>
<script>
	//键盘事件
	//onkeeydown
	//onkeyup
	//onkeypress
	//有些特殊按键onkeypress没有效果，用onkeydown和onkeyup来代替
	/*document.onkeydown = function(){
		console.log("按下");
	};
	document.onkeypress = function(e){
		console.log("按");
		console.dir(e);
		//ctrlkey是否按了Ctrl键
		//altkey是否按了alt键
		//shift是否按了shift键
		//keyCode按键的编码
		//key按键的字母
	};
	document.onkeyup = function(){
		console.log("松开");
	};*/
	var oImg = document.querySlector();
	document.onkeypress = function(e){
		console.log(e.keyCode);
		switch(e.keyCode){
			//向上
             case 38:
                 oImg.style.top = oImg.offsetTop + 5 + "px";
                 break;
             case 38:
                 oImg.style.top = oImg.offsetTop - 5 + "px";
                 break;
             case 37:
                 oImg.style.left = oImg.offsetLeft - 5 + "px";
                 break;
             case 39:
                 oImg.style.left = oImg.offsetLeft + 5 + "px";
                 break;
                 default:
                 break;
		}
	};
</script>